/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include <QApplication>

#include <QStyleFactory>
#include <QMessageBox>
#include <QTranslator>
#include <QSettings>
#include <QFileInfo>
#include <QtPlugin>
#include <QLocale>
#include <QWidget>
#include <QStyle>
#include <QDebug>
#include <QDir>
#include "frmLogin.h"
#include "config.h"
#ifdef UPDATE_MANAGER
#include <QUrl>
#include <QTimer>
#include <QProcess>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include "frmUpdate.h"
#include "UpdateThread.h"
#endif

#ifdef WithStyles
    Q_IMPORT_PLUGIN(QCleanlooksStylePlugin)
    Q_IMPORT_PLUGIN(QMotifStylePlugin)
    Q_IMPORT_PLUGIN(QPlastiqueStylePlugin)
#endif

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName(ProductName);
    a.setApplicationVersion(ProductVersion);

#ifdef SHARED
    QDir pluginsDir = QFileInfo(a.applicationFilePath()).absoluteDir();
    QDir::setCurrent(pluginsDir.path());
    pluginsDir.cd("plugins");
    a.addLibraryPath(pluginsDir.path());
#ifdef QT5
    pluginsDir.cdUp();
    pluginsDir.cd("platforms");
    a.addLibraryPath(pluginsDir.path());
    pluginsDir.cdUp();
    a.addLibraryPath(pluginsDir.path());
#endif
#ifdef MACX
    pluginsDir.cdUp();
    pluginsDir.cdUp();
    pluginsDir.cd("plugins");
    a.addLibraryPath(pluginsDir.absolutePath());
#ifdef QT5
    pluginsDir.cdUp();
    pluginsDir.cd("platforms");
    a.addLibraryPath(pluginsDir.path());
#endif
#endif
#endif

    QSettings settings(ProductVendor,ProductName);

    settings.beginGroup("Interface");
    QString language = settings.value("Language","System").toString();
    settings.endGroup();

    // Start external translate loading
    QString trplugspath = TranslationPath;
    QDir dirTr;
    trplugspath = trplugspath.replace("$ED",QFileInfo(a.applicationFilePath()).absoluteDir().absolutePath());
    trplugspath = trplugspath.replace("$WD",dirTr.absolutePath());
    qDebug() << "Translation path" << trplugspath;
    bool trsf = false;
    bool svlp = false;
    QTranslator EappTranslator;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/km_" + langList.at(0) + ".qm"))
            {
                EappTranslator.load(trplugspath + "/km_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/km_" + langList.at(0) + ".qm"))
            {
                if (!EappTranslator.load(trplugspath + "/km_" + langList.at(0) + ".qm"))
                {
                    if (langList.at(0) != "en")
                    {
                        trsf = true;
                    }
                }
                else
                {
                    svlp = true;
                }
            }
            else
            {
                if (langList.at(0) != "en")
                {
                    trsf = true;
                }
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/km_" + langList.at(0) + ".qm"))
            {
                EappTranslator.load(trplugspath + "/km_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&EappTranslator);
#ifdef QT4
    QTranslator EqtTranslator;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qt_" + langList.at(0) + ".qm"))
            {
                EqtTranslator.load(trplugspath + "/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qt_" + langList.at(0) + ".qm"))
            {
                EqtTranslator.load(trplugspath + "/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qt_" + langList.at(0) + ".qm"))
            {
                EqtTranslator.load(trplugspath + "/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&EqtTranslator);
#else
#ifdef QT5
    QTranslator EqtTranslator1;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qtbase_" + langList.at(0) + ".qm"))
            {
                EqtTranslator1.load(trplugspath + "/qtbase_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qtbase_" + langList.at(0) + ".qm"))
            {
                EqtTranslator1.load(trplugspath + "/qtbase_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qtbase_" + langList.at(0) + ".qm"))
            {
                EqtTranslator1.load(trplugspath + "/qtbase_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&EqtTranslator1);
    QTranslator EqtTranslator2;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qtmultimedia_" + langList.at(0) + ".qm"))
            {
                EqtTranslator2.load(trplugspath + "/qtmultimedia_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qtmultimedia_" + langList.at(0) + ".qm"))
            {
                EqtTranslator2.load(trplugspath + "/qtmultimedia_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(trplugspath + "/qtmultimedia_" + langList.at(0) + ".qm"))
            {
                EqtTranslator2.load(trplugspath + "/qtmultimedia_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&EqtTranslator2);
#endif
#endif
    // End external translate loading
    // Start internal translate loading
    QTranslator appTranslator;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/km_" + langList.at(0) + ".qm"))
            {
                if (!appTranslator.load(":/tr/km_" + langList.at(0) + ".qm"))
                {
                    if (langList.at(0) != "en")
                    {
                        if (svlp) {trsf = true;}
                    }
                }
            }
            else
            {
                if (langList.at(0) != "en")
                {
                    if (svlp) {trsf = true;}
                }
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/km_" + langList.at(0) + ".qm"))
            {
                appTranslator.load(":/tr/km_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/km_" + langList.at(0) + ".qm"))
            {
                appTranslator.load(":/tr/km_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&appTranslator);
#ifdef QT4
    QTranslator qtTranslator;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qt_" + langList.at(0) + ".qm"))
            {
                qtTranslator.load(":/tr/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qt_" + langList.at(0) + ".qm"))
            {
                qtTranslator.load(":/tr/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qt_" + langList.at(0) + ".qm"))
            {
                qtTranslator.load(":/tr/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&qtTranslator);
#else
#ifdef QT5
    QTranslator qtTranslator1;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qtbase_" + langList.at(0) + ".qm"))
            {
                qtTranslator1.load(":/tr/qtbase_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qtbase_" + langList.at(0) + ".qm"))
            {
                qtTranslator1.load(":/tr/qtbase_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qtbase_" + langList.at(0) + ".qm"))
            {
                qtTranslator1.load(":/tr/qtbase_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&qtTranslator1);
    QTranslator qtTranslator2;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qtmultimedia_" + langList.at(0) + ".qm"))
            {
                qtTranslator2.load(":/tr/qtmultimedia_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qtmultimedia_" + langList.at(0) + ".qm"))
            {
                qtTranslator2.load(":/tr/qtmultimedia_" + langList.at(0) + ".qm");
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qtmultimedia_" + langList.at(0) + ".qm"))
            {
                qtTranslator2.load(":/tr/qtmultimedia_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&qtTranslator2);
#endif
#endif
    // End internal translate loading

    bool noupdate = false;
    bool regupdate = false;
    bool minimized = false;
    bool resetstyle = false;

    foreach (const QString& argument, a.arguments())
    {
        if (argument == "--noupdate" || argument.left(11) == "--noupdate=")
        {
            noupdate = true;
        }
        if (argument == "--regupdate" || argument.left(12) == "--regupdate=")
        {
            regupdate = true;
        }
        if (argument == "--minimized" || argument.left(12) == "--minimized=")
        {
            minimized = true;
        }
        if (argument == "--resetstyle" || argument.left(13) == "--resetstyle=")
        {
            resetstyle = true;
        }
    }

#ifdef WIN32
    if (regupdate)
    {
        QSettings regNormal("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"+QString(ApplicationID)+"_is1",QSettings::NativeFormat);
        if (regNormal.contains("DisplayName"))
        {
            regNormal.setValue("DisplayName",a.applicationName() + " " + a.applicationVersion());
        }
        if (regNormal.contains("DisplayVersion"))
        {
            regNormal.setValue("DisplayVersion",a.applicationVersion());
        }
        QSettings reg6432Node("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"+QString(ApplicationID)+"_is1",QSettings::NativeFormat);
        if (reg6432Node.contains("DisplayName"))
        {
            reg6432Node.setValue("DisplayName",a.applicationName() + " " + a.applicationVersion());
        }
        if (reg6432Node.contains("DisplayVersion"))
        {
            reg6432Node.setValue("DisplayVersion",a.applicationVersion());
        }
    }
#else
    Q_UNUSED(noupdate);
    Q_UNUSED(regupdate);
#endif

    if (resetstyle)
    {
        settings.beginGroup("Style");
        settings.setValue("Custom", false);
        settings.setValue("showBug", true);
        settings.endGroup();
    }

#ifdef WIN32

    if (!noupdate)
    {
#ifdef ALPHA_UPDATE_MODE
        bool updateAvailable = false;
        QString newVersion;
        QString updatePath = UpdatePath;
        QString versionType = VersionType;

        QNetworkAccessManager *http = new QNetworkAccessManager();
        QNetworkReply *treply = http->get(QNetworkRequest(QUrl(updatePath + "stable" + versionType)));
        QEventLoop loop;
        QTimer::singleShot(5000, &loop, SLOT(quit()));
        QObject::connect(treply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        newVersion = QString::fromUtf8(treply->readAll());
        newVersion = newVersion.remove("\n");
        newVersion = newVersion.remove("\r");
        newVersion = newVersion.trimmed();

        if (a.applicationVersion() != newVersion && newVersion != "") {updateAvailable = true;}

        if (updateAvailable)
        {
            QStringList args;
            args.append("/C");
            args.append("KeppeScriptUpdater.exe --path=network --script=" + updatePath + versionType + "_" + newVersion + ".lua --version=" + a.applicationVersion());
            QProcess *ksu = new QProcess;
            ksu->startDetached("cmd",args);
            ksu->deleteLater();
            return 0;
        }
#endif
    }

#endif

    settings.beginGroup("Style");
    bool loadCustom = settings.value("Custom",false).toBool();
    if (loadCustom)
    {
        QString style = settings.value("Name","System").toString();
        if (style != "System")
        {
            if (style.trimmed() != "")
            {
                a.setStyle(style);
            }
        }
    }
    settings.endGroup();

    frmLogin w;
    w.languagePath = trplugspath;

#ifdef UPDATE_MANAGER
    settings.beginGroup("Update");
    bool updateNotificationEnabled = settings.value("UpdateNotification",true).toBool();

    frmUpdate *uw = new frmUpdate();
    uw->setVersionType(VersionType);

    UpdateThread *ut = new UpdateThread(VersionType, a.applicationVersion());
    if (updateNotificationEnabled)
    {
        ut->start();
    }
    else
    {
        uw->disableUpdateNotificationButton();
    }

    w.setUpdateThread(ut);
    w.setUpdateWindow(uw);

    QObject::connect(ut,SIGNAL(setNewVersion(QString)),uw,SLOT(setNewVersion(QString)));
    QObject::connect(ut,SIGNAL(updateIsNowAvailable()),uw,SLOT(show()));
    QObject::connect(uw,SIGNAL(disableUpdateNotification()),ut,SLOT(disableUpdateNotification()));

    settings.endGroup();
#endif

    if (minimized)
    {
        w.showMinimized();
    }
    else
    {
        w.show();
    }

    return a.exec();
}
